package ren.kane.phoenix.util.io;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * @author renrk(1275) on 2019-08-06 5:08 PM
 **/
public class DataInputOutputStreamTest {

    private static final int LEN = 5;

    private static void testDataOutputStream() {
        try {
            DataOutputStream outputStream = new DataOutputStream(new FileOutputStream(new File("dir", "file.txt")));
            outputStream.writeBoolean(true);
            outputStream.writeByte((byte) 0x41);
            outputStream.writeChar((char) 0x4243);
            outputStream.writeShort((short) 0x4445);
            outputStream.writeInt(0x12345678);
            outputStream.writeLong(0x0FEDCBA987654321L);
            outputStream.writeUTF("abcdefghijklmnopqrstuvwxyz严12");
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void testDataInputStream() {
        try {
            DataInputStream inputStream = new DataInputStream(new FileInputStream(new File("dir", "file.txt")));
            System.out.printf("byteToHexString(0x8F):0x%s\n", byteToHexString((byte) 0x8F));
            System.out.printf("charToHexString(0x8FCF):0x%s\n", charToHexString((char) 0x8FCF));
            System.out.printf("readBoolean():%s\n", inputStream.readBoolean());
            System.out.printf("readByte():0x%s\n", byteToHexString(inputStream.readByte()));
            System.out.printf("readChar():0x%s\n", charToHexString(inputStream.readChar()));
            System.out.printf("readShort():0x%s\n", shortToHexString(inputStream.readShort()));
            System.out.printf("readInt():0x%s\n", Integer.toHexString(inputStream.readInt()));
            System.out.printf("readLong():0x%s\n", Long.toHexString(inputStream.readLong()));
            System.out.printf("readUTF():%s\n", inputStream.readUTF());
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 打印byte对应的16进制的字符串
    private static String byteToHexString(byte val) {
        return Integer.toHexString(val & 0xff);
    }

    // 打印char对应的16进制的字符串
    private static String charToHexString(char val) {
        return Integer.toHexString(val);
    }

    // 打印short对应的16进制的字符串
    private static String shortToHexString(short val) {
        return Integer.toHexString(val & 0xffff);
    }

    public static void main(String[] args) {
        testDataOutputStream();
        testDataInputStream();
    }
}
